﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json.Linq;
using YuuzleComic.Common;
using YuuzleComic.DBUtility;

public partial class yzadmin_data_login : System.Web.UI.Page
{
    protected string json = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            switch (Request["a"])
            {
                case "check":
                    this.ProcessCheck();
                    break;
                case "login":
                    this.ProcessLogin();
                    break;
                default:
                    break;
            }
        }
    }

    private void ProcessLogin()
    {
        JObject result = new JObject();
        try
        {
            if (Session["ValidateNumber"].ToString() != Request.Form["CheckCode"])
            {
                result.Add("success", false);
                result.Add("errorMessage", "验证码错误！");
                return;
            }
            string username = Input.Filter(Request.Form["UserName"].Trim());
            string password = Input.Filter(Request.Form["PassWord"].Trim());
            SqlParameter[] parameters = new SqlParameter[] {
                new SqlParameter("username",username),
                new SqlParameter("password",password)
            };
            DataSet ds = DbHelperSQL.Query("select top(1) * from admin where username=@username and password=@password",parameters);
            if (ds.Tables[0].Rows.Count <= 0)
            {
                result.Add("success", false);
                result.Add("errorMessage", "账户或密码错误！");
                return;
            }
            else
            {
                DbHelperSQL.ExecuteSql("update admin set LoginTimes=LoginTimes+1,LoginTime=getdate(),LoginIP='" + Request.ServerVariables.Get("REMOTE_ADDR") + "' where id=" + ds.Tables[0].Rows[0]["id"]);
                Session["AdminID"] = ds.Tables[0].Rows[0]["id"];
                Session["Adminname"] = ds.Tables[0].Rows[0]["username"];
                Session["IsAdmin"] = true;
                Session["KEY"] = ds.Tables[0].Rows[0]["oskey"];
                result.Add("success", true);
            }

        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally {
            json = result.ToString();
        }
    }

    private void ProcessCheck()
    {
        JObject result = new JObject();
        result.Add("success", Session["AdminID"] != null);
        json = result.ToString();
    }
}